﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.Companies.WebParts
{
    [Guid("d841efe6-419e-41c4-871d-19ddca80805a")]
    public class IOFilters : WebPart
    {
        protected DropDownList _countiesSelector;
        protected DropDownList _partnershipSelector;
        protected DropDownList _employeesSelector;

        private readonly Dictionary<string, string> _queryParts = new Dictionary<string, string>();

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            Controls.Add(new LiteralControl("<fieldset class=\"products\">"));

            _countiesSelector = new DropDownList();
            _countiesSelector.AutoPostBack = true;
            _countiesSelector.ID = "_countiesSelector";
            _countiesSelector.DataTextField = "Title";
            _countiesSelector.DataValueField = "Title";
            _countiesSelector.SelectedIndexChanged += CountiesSelectorSelectedIndexChanged;
            Controls.Add(_countiesSelector);

            _partnershipSelector = new DropDownList();
            _partnershipSelector.Style["width"] = "150px";
            _partnershipSelector.AutoPostBack = true;
            _partnershipSelector.ID = "_partnershipSelector";
            _partnershipSelector.SelectedIndexChanged += PartnershipSelectorSelectedIndexChanged;
            Controls.Add(_partnershipSelector);

            _employeesSelector = new DropDownList();
            _employeesSelector.AutoPostBack = true;
            _employeesSelector.ID = "_employeesSelector";
            _employeesSelector.SelectedIndexChanged += EmployeesSelectorSelectedIndexChanged;
            Controls.Add(_employeesSelector);

            Controls.Add(new LiteralControl("</fieldset>"));
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            EnsureChildControls();

            var queryString = HttpContext.Current.Request.QueryString;
            var county = queryString["county"];
            var partnership = queryString["partnership"];
            var employees = queryString["emp"];

            var repository = new CompanyRepository(SPContext.Current.Web);

            _countiesSelector.DataSource = repository.GetCountyResults(); //CompanyQueryManager.GetCounties();
            _countiesSelector.DataBind();
            _countiesSelector.Items.Insert(0, new ListItem("- maakond -", string.Empty));
            if (_countiesSelector.Items.FindByValue(county) != null)
                _countiesSelector.SelectedValue = county;

            _partnershipSelector.DataSource = repository.GetPartnershipResults(); //CompanyQueryManager.GetPartnershipLevels();
            _partnershipSelector.DataBind();
            _partnershipSelector.Items.Insert(0, new ListItem("- partnerlustase -", string.Empty));

            if (_partnershipSelector.Items.FindByValue(partnership) != null)
                _partnershipSelector.SelectedValue = partnership;

            _employeesSelector.DataSource = repository.GetEmployeeResults(); // CompanyQueryManager.GetEmployees();
            _employeesSelector.DataBind();
            _employeesSelector.Items.Insert(0, new ListItem("- töötajaid -", string.Empty));
            if (_employeesSelector.Items.FindByValue(employees) != null)
                _employeesSelector.SelectedValue = employees;
        }

        protected void EmployeesSelectorSelectedIndexChanged(object sender, EventArgs e)
        {
            _queryParts["emp"] = _employeesSelector.SelectedValue;
            RedirectToQuery();
        }

        protected void PartnershipSelectorSelectedIndexChanged(object sender, EventArgs e)
        {
            _queryParts["partnership"] = _partnershipSelector.SelectedValue;
            RedirectToQuery();
        }

        protected void CountiesSelectorSelectedIndexChanged(object sender, EventArgs e)
        {
            _queryParts["county"] = _countiesSelector.SelectedValue;
            RedirectToQuery();
        }

        protected void RedirectToQuery()
        {
            var newQueryParts = new List<string>();

            var queryValues = HttpContext.Current.Request.QueryString;
            foreach (var key in queryValues.AllKeys)
            {
                if (_queryParts.ContainsKey(key))
                    continue;
                newQueryParts.Add(key + "=" + HttpUtility.UrlEncode(queryValues[key]));
            }
            foreach (var elem in _queryParts)
            {
                newQueryParts.Add(elem.Key + "=" + HttpUtility.UrlEncode(elem.Value));
            }

            var queryString = string.Join("&", newQueryParts.ToArray());
            HttpContext.Current.Response.Redirect("default.aspx?" + queryString);
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            return;
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            return;
        }
    }
}
